package com.aoxon.cargo.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aoxon.cargo.R;
import com.aoxon.cargo.adapter.SupMessageListAdapter;
import com.aoxon.cargo.bean.GsonBean;
import com.aoxon.cargo.bean.SystemMessage;
import com.aoxon.cargo.cache.SupCache;
import com.aoxon.cargo.loader.NormalDataLoader;
import com.aoxon.cargo.service.MyServiceFactory;
import com.aoxon.cargo.service.SystemMessageService;
import com.aoxon.cargo.state.MyStateUtil;
import com.aoxon.cargo.util.CheckStateUtil;
import com.aoxon.cargo.util.DataUtil;
import com.aoxon.cargo.util.ToastUtil;
import com.google.gson.reflect.TypeToken;

/**
 * 系统消息显示列表界面
 * 
 * @author ZZJ
 * 
 */
public class SupSystemMessageListActivity extends BaseActivity implements
		NormalDataLoader.OnLoadDataListener {

	private int length = 20;
	private int startIndex = 0;
	private int visibleLastIndex;
	private boolean isReachLast = false;

	private ImageView ivReturnButton;

	private TextView tvTitle;
	private TextView tvListBottom;

	private ProgressBar pbListBottom;
	private ListView lvSystemMessageList;
	private RelativeLayout rlListBottom;

	private LayoutInflater layoutInflater;
	private SupMessageListAdapter adapter;

	private NormalDataLoader normalDataLoader = new NormalDataLoader(this);

	private List<SystemMessage> messageList = new ArrayList<SystemMessage>();

	private SystemMessageService systemMessageService = (SystemMessageService) MyServiceFactory
			.getInstance(MyServiceFactory.SYSTEM_MESSAGE);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setup();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	/**
	 * 自定义方法
	 * ******************************************************************************************************************************************/

	private void setup() {
		setContentView(R.layout.sup_system_message_list);

		ivReturnButton = (ImageView) findViewById(R.id.ivPublicTitleReturn);
		tvTitle = (TextView) findViewById(R.id.tvPublicTiTle);

		lvSystemMessageList = (ListView) findViewById(R.id.lvSystemMessageList);
		layoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
		rlListBottom = (RelativeLayout) layoutInflater.inflate(
				R.layout.pub_list_bottom, null);
		tvListBottom = (TextView) rlListBottom.findViewById(R.id.tvListBottom);
		pbListBottom = (ProgressBar) rlListBottom
				.findViewById(R.id.pbListBottom);

		adapter = new SupMessageListAdapter(this, messageList);

		normalDataLoader.setOnloadDataListener(this);

		tvTitle.setText("系统消息");
		lvSystemMessageList.addFooterView(rlListBottom);
		lvSystemMessageList.setAdapter(adapter);
		adapter.notifyDataSetChanged();
		lvSystemMessageList.setOnScrollListener(myScrollListener);
		lvSystemMessageList.setOnItemClickListener(myItemClickListener);
		ivReturnButton.setOnClickListener(myClickListener);

		normalDataLoader.load();
	}

	/**
	 * 滚动监听
	 */
	OnScrollListener myScrollListener = new OnScrollListener() {

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			switch (scrollState) {
			case OnScrollListener.SCROLL_STATE_FLING:
				adapter.setBusy(true);
				break;
			case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
				adapter.setBusy(false);
				break;
			case OnScrollListener.SCROLL_STATE_IDLE:
				int lastIndex = adapter.getCount();
				adapter.setBusy(false);
				if (visibleLastIndex == lastIndex && !isReachLast) {
					normalDataLoader.load();
				}
				break;
			default:
				break;
			}
			adapter.notifyDataSetChanged();
		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			visibleLastIndex = firstVisibleItem + visibleItemCount - 1;
		}
	};

	/**
	 * 系统按键的设置
	 * *****************************************************************************************************************************************/

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			Intent intent = new Intent(getBaseContext(), SupIndexActivity2.class);
			startActivity(intent);
			this.finish();
			return false;
		}
		return false;
	}

	/**
	 * 选项点击监听
	 */
	OnItemClickListener myItemClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			if ((adapter.getCount() != position)) {
				SupCache.systemMessage = messageList.get(position);
				Intent intent = new Intent(getBaseContext(),
						SupSystemMessageDetailActivity.class);
				startActivity(intent);
				SupSystemMessageListActivity.this.finish();
			}
		}

	};

	/**
	 * 设置控件的点击监听
	 */
	OnClickListener myClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.ivPublicTitleReturn:
				Intent intent = new Intent(getBaseContext(),
						SupIndexActivity2.class);
				startActivity(intent);
				SupSystemMessageListActivity.this.finish();
				break;

			default:
				break;
			}

		}
	};

	@Override
	public void beforeLoad() {
		// TODO Auto-generated method stub
		pbListBottom.setVisibility(View.VISIBLE);
		tvListBottom.setText("加载中～");
	}

	@Override
	public void toLoad(Message msg) throws Exception {
		// TODO Auto-generated method stub
		GsonBean gsonBean = systemMessageService.execute(startIndex, length);
		if (CheckStateUtil.check(gsonBean)) {
			List<SystemMessage> messages = DataUtil.gson.fromJson(
					gsonBean.getStrJson(),
					new TypeToken<List<SystemMessage>>() {
					}.getType());
			startIndex += messages.size();
			messageList.addAll(messages);
			msg.what = MyStateUtil.LIST_CHANGE;
		} else {
			// 查找不到数据的情况
			isReachLast = true;
			msg.what = MyStateUtil.LIST_IS_REACH_LAST;
		}
	}

	@Override
	public void afterLoad(int state) {
		// TODO Auto-generated method stub
		pbListBottom.setVisibility(View.GONE);
		switch (state) {
		case MyStateUtil.LIST_CHANGE:
			Log.i("listChange",
					"------------------listChange--------------------");
			tvListBottom.setText("向上拉加载数据");
			break;
		case MyStateUtil.LIST_IS_REACH_LAST:
			tvListBottom.setText("没有相应数据咯～");
			break;
		case MyStateUtil.NOT_NET_CONNECTION:
			tvListBottom.setText("无网络连接～");
			break;
		case MyStateUtil.ERROR_NET_CONNECTION:
			tvListBottom.setText("向上拉加载数据");
			ToastUtil.show(getBaseContext(), "网络连接异常");
			break;
		default:
			break;
		}
		adapter.notifyDataSetChanged();
	}

}
